

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:reabampos/src/reabam/operation/rb_config.dart';
import 'package:reabampos/src/reabam/ui_self_service/shoppingcart/pagestate_ss_manual_add_cartrelateditem.dart';
import 'package:reabampos/src/reabam/ui_self_service/shoppingcart/pagestate_ss_manual_input_gooditem_barcode_search.dart';
import 'package:reabampos/src/reabam/ui_self_service/shoppingcart/pagestate_ss_pay.dart';
import 'package:reabampos/src/reabam/utils/brean/c_bean_good_item.dart';
import 'package:reabampos/src/reabam/utils/rb_business.dart';
import 'package:reabampos/src/reabam/utils/rb_color.dart';
import 'package:reabampos/src/reabam/utils/rb_widget_ss.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_string.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';

/*
购物车
 */
class PageStateSelfServiceShoppingCart extends XPageState{

  /*
  {
			"superMemberId":null,
			"companyName":"广州荔湾丽湖（外卖专用)",
			"regionName":"",
			"consigneeName":"",
			"cityName":"",
			"integral":0.0,
			"consigneePhone":"16666666212",
			"memberId":"fdb11ff8c9954bc9a0160b90a703284c",
			"createDate":"2024-04-03 15:07:42",
			"isQrCode":0,
			"gradeName":"高级萌新2",
			"address":"",
			"consumeAmount":0.0,
			"consigneeAddr":"",
			"sysTags":null,
			"sex":"",
			"headImage":"",
			"userName":"MMM",
			"tags":[],
			"companyId":"5ad586a8721e49518998aedef9fd3b5c",
			"phone":"16666666212",
			"grade":"S06602",
			"corporateMember":false,
			"provinceName":"",
			"applyStatus":null,
			"createName":"",
			"status":"Y"
		}
   */
  Map<String,dynamic>? member;

  PageStateSelfServiceShoppingCart({required this.member});

  late XFunctionNotifyStateChangeListener listener_updateShoppingcart;

  @override
  void onCreate() {
    super.onCreate();
    RBConfigs.isPageScanType=1;
    RBBusinessUtils.list_shoppingcart_selfService.clear();
    RBBusinessUtils.shoppingcartInfo_selfService.clear();

    RBBusinessUtils.memberId=member?['memberId'];

    listener_updateShoppingcart=(String key,dynamic value){
      //通知更新购物车
      updateData();
    };

    XNotifyStateChangeUtils.receiveChangeNotify(
        action: RBConfigs.NotifyAction_selfService_update_shoppingcart,
        listener: listener_updateShoppingcart
    );
  }

  @override
  void onResumed() {
    super.onResumed();
    RBConfigs.isPageScanType=1;
  }
  @override
  void onDestroy() {
    super.onDestroy();
    XNotifyStateChangeUtils.unReceiveChangeNotify(
        action: RBConfigs.NotifyAction_selfService_update_shoppingcart,
        listener: listener_updateShoppingcart
    );
  }

  @override
  void onStart() {
    setXTopBarWidget(
        height: null,
        child: XWidgetUtils.getLayoutColumn(
            children: [
              RBWidgets_SelfService.getTitleBarWidget(
                this,
                isShowLeftBt: false,
                title: XSharePreferencesUtils.getString(RBConfigs.SP_CompanyName),
                isTitleAlignmentCenter:false,
                backgroundColor: RBColors.reabamColor4,
                rightWidget: XWidgetUtils.getWidgetTimerButton(
                    timeout_s: 120,
                    defaultName: '退出结账',
                    fontColor: Colors.white,
                    fontSize: 34,
                    defaultBackgroundColor:RBColors.reabamColor4,
                    borderColor: Colors.white,
                    width: 280,
                    height: 80,
                    tag_action_receive_notify:RBConfigs.Tag_action_receive_notify_shoppingcart_exit_button,
                    onClick: (r1){
                      finishPage(backToPointPageName: 'StatePageSelfServiceHomeIndex');
                    },
                    onTimerComplete: (r1){
                      finishPage(backToPointPageName: 'StatePageSelfServiceHomeIndex');
                    }
                ),
              ),
              member==null?XWidgetUtils.getLayoutContainer():XWidgetUtils.getLayoutContainer(
                  margin: XWidgetUtils.getEdgeInsets(30, 20, 30, 10),
                  child: XWidgetUtils.getXLayoutRoundedRect(
                      radius_topLeft: 16,
                      radius_topRight: 16,
                      radius_bottomRight: 16,
                      radius_bottomLeft: 16,
                      padding: XWidgetUtils.getEdgeInsets(30, 0, 30, 0),
                      height: 100,
                      alignment: Alignment.center,
                      child: XWidgetUtils.getLayoutRow(
                          children: [
                            XImageUtils.getImageWidgetWithAsset(
                              'ss_member.png',
                              width: 70,
                              height: 70,
                            ),
                            XWidgetUtils.getLayoutExpanded(
                              XWidgetUtils.getWidgetText(
                                '${member!['userName']} ${member!['phone']}',
                                style: XStyleUtils.getTextStyle(
                                  fontSize: 34,
                                  color: RBColors.reabamColor4,
                                ),
                                padding: XWidgetUtils.getEdgeInsets(13, 0, 0, 0),
                              ),
                            )
                          ]
                      )
                  )
              )
            ]
        )
    );
  }

  @override
  void rebuildItemWidget() {
    //bottombar
    List<Widget> list_bottom_bars=[];
    list_bottom_bars.add(
        XWidgetUtils.getLayoutExpanded(
            XWidgetUtils.getWidgetGestureDetector(
                child: XWidgetUtils.getLayoutContainer(
                    alignment: Alignment.center,
                    backgroundColor: Colors.white,
                    child: XWidgetUtils.getLayoutRow(
                        mainAxisSize:MainAxisSize.min,
                        mainAxisAlignment:MainAxisAlignment.center,
                        children: [
                          XImageUtils.getImageWidgetWithAsset(
                            'ss_input_good_barcode.png',
                            width: 44,
                            height: 44,
                          ),
                          XWidgetUtils.getWidgetText(
                            '手输入条形码',
                            style: XStyleUtils.getTextStyle(
                              fontSize: 30,
                              color: XColorUtils.color333333,
                            ),
                            padding: XWidgetUtils.getEdgeInsets(18, 0, 0, 0),
                          )
                        ]
                    )
                ),
                onTap: (){

                  //
                  notifyExitButtonRestartTimer();

                  startPage(
                      PageStateSelfServiceManualInputGoodItemBarcodeSearch(),
                      resultCallback: (res){
                        if(res!=null){
                          //扫描搜索商品添加购物车
                          RBBusinessUtils.scanFindGood_and_addToShoppingcart_selfService(this,res);
                        }
                      }
                  );
                }
            )
        )
    );

    bool cartEnableOptionalItems=XSharePreferencesUtils.getBool(RBConfigs.SP_cartEnableOptionalItems);
    if(cartEnableOptionalItems){

      String cartRelatedItem_json=XSharePreferencesUtils.getString(RBConfigs.SP_cartRelatedItem);
      Map<String,dynamic> map_cartRelatedItem=XJsonUtils.json2Map(cartRelatedItem_json);
      String? cartRelatedItemAlias=!XStringUtils.isEmpty(map_cartRelatedItem['cartRelatedItemAlias'])?map_cartRelatedItem['cartRelatedItemAlias']:map_cartRelatedItem['cartRelatedItemName'];
      String? cartRelatedItemId=map_cartRelatedItem['cartRelatedItemId'];

      if(!XStringUtils.isEmpty(cartRelatedItemAlias)){
        list_bottom_bars.add(XWidgetUtils.getWidgetDividerVertical(height: 90,width:1));
        list_bottom_bars.add(
            XWidgetUtils.getLayoutExpanded(
                XWidgetUtils.getWidgetGestureDetector(
                    child: XWidgetUtils.getLayoutContainer(
                        alignment: Alignment.center,
                        backgroundColor: Colors.white,
                        child: XWidgetUtils.getLayoutRow(
                            mainAxisSize:MainAxisSize.min,
                            mainAxisAlignment:MainAxisAlignment.center,
                            children: [
                              XImageUtils.getImageWidgetWithAsset(
                                'ss_add_other_good.png',
                                width: 44,
                                height: 44,
                              ),
                              XWidgetUtils.getWidgetText(
                                cartRelatedItemAlias!,
                                style: XStyleUtils.getTextStyle(
                                  fontSize: 30,
                                  color: XColorUtils.color333333,
                                ),
                                padding: XWidgetUtils.getEdgeInsets(18, 0, 0, 0),
                              )
                            ]
                        )
                    ),
                    onTap: (){
                      notifyExitButtonRestartTimer();
                      startPage(
                          PageStateSelfServiceManualAddCartRelatedItem(cartRelatedItemAlias??'',cartRelatedItemId??''),
                          resultCallback: (res){
                            if(res!=null){
                              //添加购物车
                              for(ComponentBeanGoodItem iitem in res){
                                if(iitem.currentQuantity>0){
                                  RBBusinessUtils.addToShoppingCart_selfService(iitem);
                                }
                              }
                              updateData();
                            }
                          }
                      );


                    }
                )
            )
        );
      }

    }

    setXBottomBarWidget(
        backgroundColor: Colors.white,
        height: 310,
        child: XWidgetUtils.getLayoutContainer(
            decoration: XWidgetUtils.getBoxDecoration(
                border: Border(
                    top: BorderSide(
                        color: XColorUtils.dividerColor
                    )
                )
            ),
            child: XWidgetUtils.getLayoutColumn(
                children: [
                  XWidgetUtils.getLayoutContainer(
                      height: 90,
                      alignment: Alignment.center,
                      child: XWidgetUtils.getLayoutRow(
                          children: list_bottom_bars
                      )
                  ),
                  XWidgetUtils.getLayoutExpanded(
                    XWidgetUtils.getLayoutContainer(
                        decoration: XWidgetUtils.getBoxDecoration(
                            border: Border(
                                top: BorderSide(
                                    color: XColorUtils.dividerColor
                                )
                            )
                        ),
                        alignment: Alignment.center,
                        padding: XWidgetUtils.getEdgeInsets(60, 0, 60, 0),
                        child: XWidgetUtils.getLayoutRow(
                            children: [
                              XWidgetUtils.getWidgetText(
                                '¥${XNumberUtils.formatDoubleX(RBBusinessUtils.shoppingcartInfo_selfService['totalMoney']??0, n: 2)}',
                                style: XStyleUtils.getTextStyle(
                                    fontSize:34,
                                    color: const Color(0xFFFF0020),
                                    fontWeight: FontWeight.bold
                                ),
                                padding: XWidgetUtils.getEdgeInsets(0, 0, 13, 0),
                              ),
                              XWidgetUtils.getLayoutExpanded(
                                XWidgetUtils.getWidgetText(
                                  '共${XNumberUtils.formatDoubleX(RBBusinessUtils.shoppingcartInfo_selfService['totalQuantity']??0, n: 0)}件',
                                  style: XStyleUtils.getTextStyle(
                                    fontSize:30,
                                    color: XColorUtils.color333333,
                                  ),
                                ),
                              ),
                              XWidgetUtils.getWidgetGestureDetector(
                                  child: XWidgetUtils.getXLayoutRoundedRect(
                                      radius_bottomLeft: 16,
                                      radius_bottomRight: 16,
                                      radius_topRight: 16,
                                      radius_topLeft: 16,
                                      width: 400,
                                      height: 120,
                                      alignment: Alignment.center,
                                      backgroundColor: RBBusinessUtils.list_shoppingcart_selfService.isNotEmpty?RBColors.reabamColor4:const Color(0xFFADB1C0),
                                      child: XWidgetUtils.getWidgetText(
                                          '确认结算',
                                          style: XStyleUtils.getTextStyle(
                                            fontSize: 46,
                                            color: Colors.white,
                                          )
                                      )
                                  ),
                                  onTap: (){
                                    if(RBBusinessUtils.list_shoppingcart_selfService.isEmpty){
                                      return;
                                    }

                                    //暂停计时
                                    notifyExitButtonStopTimer();
                                    startPage(
                                        PageStateSelfServicePay(),
                                        resultCallback: (res){
                                          //重新开始计时
                                          notifyExitButtonRestartTimer();
                                        }
                                    );
                                  }
                              )
                            ]
                        )
                    ),
                  )
                ]
            )
        )
    );

  }

  @override
  Future<void> updateData({int pageIndex=1}) async {

    setState(() {

      if(RBBusinessUtils.list_shoppingcart_selfService.isNotEmpty){
        setXStackPageTopIndexWidget(null);
      }else{
        //没有商品时
        setXStackPageTopIndexWidget(
            XWidgetUtils.getLayoutPositioned(
                top: 566,
                left: 0,
                child: XWidgetUtils.getLayoutContainer(
                    height: 757,
                    margin: XWidgetUtils.getEdgeInsets(220, 0, 220, 0),
                    alignment: Alignment.center,
                    child: XWidgetUtils.getLayoutColumn(
                        crossAxisAlignment :CrossAxisAlignment.center,
                        children: [
                          XWidgetUtils.getLayoutExpanded(
                            XWidgetUtils.getLayoutContainer(
                                alignment: Alignment.topCenter,
                                child: XWidgetUtils.getWidgetText(
                                    '请在下方扫码区扫描产品条形码',
                                    style: XStyleUtils.getTextStyle(
                                      fontSize: 40,
                                      color: XColorUtils.color333333,
                                    )
                                )
                            ),
                          ),
                          XImageUtils.getImageWidgetWithAsset(
                            'ss_shoppingcart_bg_logo.png',
                            width: 640,
                            height: 640,
                          )
                        ]
                    )
                )
            )
        );
      }

      //
      RBBusinessUtils.updateShoppingCartInfo_selfService();

      //重设自动退出计时
      notifyExitButtonRestartTimer();
    });

  }


  @override
  Widget getBodyWidget(BuildContext context) {
    return XWidgetUtils.getLayoutContainer(
        margin: XWidgetUtils.getEdgeInsets(30, 10, 30, 10),
        child:XWidgetUtils.getWidgetListView(
            listData: RBBusinessUtils.list_shoppingcart_selfService,
            listItemWidgetFunction: (BuildContext context, int index){
              ComponentBeanGoodItem item=RBBusinessUtils.list_shoppingcart_selfService[index];

              return XWidgetUtils.getXLayoutRoundedRect(
                radius_bottomLeft: 16,
                radius_bottomRight: 16,
                radius_topRight: 16,
                radius_topLeft: 16,
                alignment: Alignment.centerLeft,
                padding: XWidgetUtils.getEdgeInsets(30, 35, 30, 35),
                margin: XWidgetUtils.getEdgeInsets(0, 10, 0, 10),
                child: XWidgetUtils.getLayoutRow(
                    crossAxisAlignment:CrossAxisAlignment.start,
                    children: [
                      XWidgetUtils.getLayoutExpanded(
                          XWidgetUtils.getLayoutContainer(
                              margin: XWidgetUtils.getEdgeInsets(0, 0, 15, 0),
                              child: XWidgetUtils.getLayoutColumn(
                                  shrinkWrap:true,
                                  children: [
                                    XWidgetUtils.getWidgetText(
                                        item.itemName??'',
                                        style: XStyleUtils.getTextStyle(
                                          fontSize: 34,
                                          color: XColorUtils.color333333,
                                          fontWeight: FontWeight.bold,
                                        )
                                    ),
                                    XStringUtils.isEmpty(item.specName)?XWidgetUtils.getLayoutContainer():
                                    XWidgetUtils.getWidgetText(
                                        item.specName??'',
                                        style: XStyleUtils.getTextStyle(
                                          fontSize: 34,
                                          color: XColorUtils.color333333,
                                        )
                                    ),
                                  ]
                              )
                          )
                      ),
                      XWidgetUtils.getLayoutColumn(
                          shrinkWrap:true,
                          crossAxisAlignment :CrossAxisAlignment.end,
                          children: [
                            XWidgetUtils.getLayoutRow(
                                children: [
                                  XWidgetUtils.getWidgetText(
                                    '¥${item.dealPrice}/${item.unit}',
                                    style: XStyleUtils.getTextStyle(
                                      fontSize: 30,
                                      color: XColorUtils.color666666,
                                    ),
                                    padding: XWidgetUtils.getEdgeInsets(0, 0, 15, 0),
                                  ),
                                  XWidgetUtils.getWidgetGestureDetector(
                                      child: XImageUtils.getImageWidgetWithAsset(
                                        'ss_shoppingcart_del.png',
                                        width: 42,
                                        height: 42,
                                      ),
                                      onTap: (){
                                        RBBusinessUtils.list_shoppingcart_selfService.remove(item);
                                        updateData();
                                      }
                                  )
                                ]
                            ),
                            RBWidgets_SelfService.getCountChangeWidget(
                                margin: XWidgetUtils.getEdgeInsets(0, 16, 0, 7),
                                text: XNumberUtils.formatDoubleX(item.currentQuantity),
                                onClick: (btN) {
                                  if(btN=='-'){

                                    if(item.currentQuantity<=1){
                                      RBBusinessUtils.list_shoppingcart_selfService.remove(item);
                                    }else{
                                      item.currentQuantity=XNumberUtils.sub(item.currentQuantity, 1);
                                    }
                                    updateData();

                                  }else if(btN=='+'){
                                    item.currentQuantity=XNumberUtils.add(item.currentQuantity, 1);
                                    updateData();
                                  }
                                }
                            ),
                            XWidgetUtils.getWidgetText(
                              '小计 ¥${XNumberUtils.formatDoubleX(item.currentMoney,n: 2)}',
                              style: XStyleUtils.getTextStyle(
                                fontSize: 30,
                                color: XColorUtils.color666666,
                              ),
                            ),
                          ]
                      ),
                    ]
                ),


              );
            }
        )
    );

  }


  void notifyExitButtonRestartTimer(){
    XNotifyStateChangeUtils.notifyStateChange(
        action: RBConfigs.Tag_action_receive_notify_shoppingcart_exit_button,
        key: 'restartTimer',
        value: 'value'
    );
  }
  void notifyExitButtonStopTimer(){
    XNotifyStateChangeUtils.notifyStateChange(
        action: RBConfigs.Tag_action_receive_notify_shoppingcart_exit_button,
        key: 'stopTimer',
        value: 'value'
    );
  }


}